package main

import (
	"io"
	"log"
	"net"
	//	"os"
	//	"regexp"
	//	"strconv"
)

var (
	srcAddr = "127.0.0.1"
	srcPort = "8081"
	dstAddr = "192.168.99.100"
	dstPort = "22"
)

func main() {
	//	ip := "127.0.0.1"
	//	port := "8081"
	listen, err := net.Listen("tcp", srcAddr+":"+srcPort)

	if err != nil {
		log.Fatalln(err)
		return
	}
	log.Println("init")

	for {
		client, err := listen.Accept()
		if err != nil {
			log.Fatalln("accept error:", err.Error())
			continue
		}
		log.Printf("accept from %s", client.RemoteAddr())

		go Channal(client, dstAddr, dstPort)
	}
}

func Channal(client net.Conn, addr string, port string) {
	//	addr := "192.168.99.100"
	//	port := "22"

	conn, err := net.Dial("tcp", addr+":"+port)
	if err != nil {
		log.Fatalln("connection error: ", err.Error())
		client.Close()
		return
	}

	Pipe(client, conn)
}

func Pipe(src, dst net.Conn) error {

	done := make(chan error, 1)

	cp := func(r, w net.Conn, opType int8) {
		n, err := io.Copy(r, w)
		log.Printf("copied %d bytes from %s to %s", n, r.RemoteAddr(), w.RemoteAddr())
		done <- err
	}

	go cp(src, dst, 1)
	go cp(dst, src, 2)

	readDone := <-done
	writeDone := <-done
	if readDone != nil {
		return readDone
	}
	if writeDone != nil {
		return writeDone
	}
	return nil
}

func connection_logger(data chan []byte, conn_n int, local_info, remote_info string) {
	log_name := fmt.Sprintf("log-%s-%04d-%s-%s.log", format_time(time.Now()), conn_n, local_info, remote_info)
	logger_loop(data, log_name)
}
func binary_logger(data chan []byte, conn_n int, peer string) {
	log_name := fmt.Sprintf("log-binary-%s-%04d-%s.log", format_time(time.Now()), conn_n, peer)
	logger_loop(data, log_name)
}

func logger_loop(data chan []byte, log_name string) {
	f, err := os.Create(log_name)
	if err != nil {
		log.Printf("Unable to create file %s, %v\n", log_name, err)
	}
	defer f.Close()
	for {
		b := <-data
		if len(b) == 0 {
			break
		}
		f.Write(b)
		f.Sync()
	}
}

func format_time(t time.Time) string {
	return t.Format("2006.01.02-15.04.05")
}
